//导入路由
import { createRouter, createWebHistory } from "vue-router";
//导入vue页面
import HomePanel from '../components/HomePanel.vue'
import Home from '../components/Home.vue'
import Login from '../components/Login.vue'
import MessageBoard from '../components/MessageBoard.vue'
import CallMe from '../components/CallMe.vue'
import Task from '../components/Task.vue'
import PersonalCenter from '../components/PersonalCenter.vue'
//设置路由集合
const routes = [
    {
        path: '/', component: HomePanel,
        children: [
            {
                path: '/Home', component: Home
            }, {
                path: '/MessageBoard', component: MessageBoard
            }, {
                path: '/CallMe', component: CallMe
            }, {
                path: '/Task', component: Task
            }, {
                path: '/PersonalCenter', component: PersonalCenter
            }]
    },
    { path: '/Login', component: Login }
]
//创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes: routes
})
import { useStore } from 'vuex'
const store = useStore()

//导航守卫
router.beforeEach((to, from, next) => {
    const isLogin = sessionStorage.getItem('userId') ?? false;
    if (isLogin) {
        // 用户已登录
        if (to.path.toLowerCase() === '/login') {
            // 如果已登录且要前往登录页，重定向到主页
            next('/Home');
        } else {
            if (to.matched.length !== 0) {
                next();
            } else {
                next('/Home');
            }
        }
    } else {
        // 用户未登录，重定向到登录页
        if (to.path.toLowerCase() !== '/login') {
            next('/Login');
        }
        // 已在登录页，正常导航
        next();
    }
})

//导出默认路由规则
export default router
